package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"perfect-vue-admin/global"
	"perfect-vue-admin/global/response"
	"perfect-vue-admin/model"
	"perfect-vue-admin/model/request"
	resp "perfect-vue-admin/model/response"
	"perfect-vue-admin/service"
	"perfect-vue-admin/utils"
)

// @Tags SysUser
// @Summary 用户修改密码
// @Security ApiKeyAuth
// @Produce  application/json
// @Param data body request.ChangePasswordStruct true "用户修改密码"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/changePassword [put]
func ChangePassword(c *gin.Context) {
	var params request.ChangePasswordStruct
	_ = c.ShouldBindJSON(&params)
	UserVerify := utils.Rules{
		"Username":    {utils.NotEmpty()},
		"Password":    {utils.NotEmpty()},
		"NewPassword": {utils.NotEmpty()},
	}
	UserVerifyErr := utils.Verify(params, UserVerify)
	if UserVerifyErr != nil {
		response.FailWithMessage(UserVerifyErr.Error(), c)
		return
	}
	U := &model.SysUser{Username: params.Username, Password: params.Password}
	if err, _ := service.ChangePassword(U, params.NewPassword); err != nil {
		response.FailWithMessage("修改失败，请检查用户名密码", c)
	} else {
		response.OkWithMessage("修改成功", c)
	}
}

// @Tags SysUser
// @Summary 分页获取用户列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "分页获取用户列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/getUserList [post]
func GetUserList(c *gin.Context) {
	var pageInfo request.PageInfo
	if err := c.ShouldBind(&pageInfo); err != nil{
		response.FailWithMessage("参数有误", c)
		return
	}
	err, list, total := service.GetUserInfoList(pageInfo)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("获取数据失败，%v", err), c)
	} else {
		response.OkWithData(resp.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, c)
	}
}

func GetUserListByIds(c *gin.Context)  {
	var ids_str []string
	ids_str, ok := c.GetQueryArray("ids[]")
	if !ok {
		response.FailWithMessage("参数解析有误", c)
		return
	}
	var ids []int
	for _, id := range ids_str {
		x, _ := utils.StringToInt(id)
		ids = append(ids, x)
	}
	userList, err := service.GetUserListByIds(ids)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		global.LOG.Error(err.Error())
		return
	}
	response.OkDetailed(userList, "获取成功", c)
	return
}

// @Tags SysUser
// @Summary 设置用户权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SetUserAuth true "设置用户权限"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/setUserAuthority [post]
func SetUserAuthority(c *gin.Context) {
	var sua request.SetUserAuth
	_ = c.ShouldBindJSON(&sua)
	UserVerify := utils.Rules{
		"UUID":        {utils.NotEmpty()},
		"AuthorityId": {utils.NotEmpty()},
	}
	UserVerifyErr := utils.Verify(sua, UserVerify)
	if UserVerifyErr != nil {
		response.FailWithMessage(UserVerifyErr.Error(), c)
		return
	}
	err := service.SetUserAuthority(sua.UUID, sua.AuthorityId)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("修改失败，%v", err), c)
	} else {
		response.OkWithMessage("修改成功", c)
	}
}

// @Tags SysUser
// @Summary 删除用户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "删除用户"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/deleteUser [delete]
func DeleteUser(c *gin.Context) {
	var reqId request.GetById
	_ = c.ShouldBindJSON(&reqId)
	IdVerifyErr := utils.Verify(reqId, utils.CustomizeMap["IdVerify"])
	if IdVerifyErr != nil {
		response.FailWithMessage(IdVerifyErr.Error(), c)
		return
	}
	err := service.DeleteUser(reqId.Id)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("删除失败，%v", err), c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// @Tags SysUser
// @Summary 删除用户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysUser true "删除用户"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/setUserInfo [put]
func SetUserInfo(c *gin.Context) {
	var user model.SysUser
	if err := c.ShouldBindJSON(&user); err != nil {
		response.FailWithMessage("参数接收失败", c)
		return
	}
	err, ReqUser := service.SetUserInfo(user)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("更新失败，%v", err), c)
	} else {
		response.OkWithData(gin.H{
			"userInfo": ReqUser,
		}, c)
	}
	return
}

func SetUserState(c *gin.Context){
	var user request.StateForm
	err := c.BindJSON(&user)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("获取数据失败，%v", err), c)
		return
	}
	err = service.ChangeUserState(user)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("更新状态失败，%v", err), c)
	}else {
		response.OkWithMessage("更新用户状态成功！", c)
	}
	return
}

func UploadUserAvatar(c *gin.Context) {
	user_id, ok := c.GetPostForm("user_id")
	file, err := c.FormFile("img")
	if ok && err == nil {
		filepath := "static/upload/avatar/"+ user_id + ".png"
		if err := c.SaveUploadedFile(file, filepath); err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}else{
			// 更新用户头像数据
			avatar_url := "/"+ filepath
			err := global.DB.Model(&model.SysUser{}).Where("id = ?", user_id).Update("header_img", avatar_url).Error
			if err != nil {
				response.FailWithMessage(err.Error(), c)
			}else {
				response.OkWithData(gin.H{"msg": "头像上传成功", "img_path": avatar_url}, c)
			}
			return
		}
	}else{
		response.FailWithMessage("参数接收失败", c)
	}
	return
}

func DeleteUserList(c *gin.Context) {
	var ids []int
	if err := c.ShouldBindJSON(&ids); err != nil{
		response.FailWithMessage("参数有误", c)
		return
	}
	err := service.BatchDeleteUsers(ids)
	if err != nil {
		response.FailWithMessage("修改失败, " + err.Error(), c)
		return
	}
	response.OkWithMessage( "删除成功", c)
	return
}

func CleanUsers(c *gin.Context)  {
	clean_confim := request.CleanConfirm{}
	if err := c.ShouldBindJSON(&clean_confim); err == nil && clean_confim.Clean {
		if err := service.CleanUsers(); err == nil {
			response.OkWithMessage("清空成功", c)
			return
		}
	}
	response.FailWithMessage("清空失败", c)
	return
}


